package org.apache.flink.runtime.resourceconsumer.runner;

import java.util.Objects;

import javax.annotation.Nullable;

import org.apache.flink.runtime.allocation.ResourceAllocation;
import org.apache.flink.runtime.allocation.ResourceAllocationStatistics;
import org.apache.flink.util.Preconditions;

/**
 * @类名: ResourceConsumerRunnerResult
 * @说明: 资源消费runner结果
 *
 * @author   leehom
 * @Date	 2023年11月7日 下午2:41:29
 * 修改记录：
 *
 * @see 	 
 */
public final class ResourceConsumerRunnerResult {

    private final ResourceAllocation allocation;

    @Nullable private final Throwable failure;

    private ResourceConsumerRunnerResult(
    		ResourceAllocation allocation, @Nullable Throwable failure) {
        this.allocation = allocation;
        this.failure = failure;
    }

    public boolean isSuccess() {
        return failure == null;
    }

    public boolean isInitializationFailure() {
        return failure != null;
    }

    public ResourceAllocation getResourceAllocation() {
        return allocation;
    }
    
    public ResourceAllocationStatistics getResourceAllocationStatistics() {
        return allocation.stat();
    }

    /**
     * This method returns the initialization failure.
     *
     * @return the initialization failure
     * @throws IllegalStateException if the result is not an initialization failure
     */
    public Throwable getInitializationFailure() {
        Preconditions.checkState(isInitializationFailure());
        return failure;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ResourceConsumerRunnerResult that = (ResourceConsumerRunnerResult) o;
        return Objects.equals(allocation, that.allocation)
                && Objects.equals(failure, that.failure);
    }

    @Override
    public int hashCode() {
        return Objects.hash(allocation, failure);
    }

    public static ResourceConsumerRunnerResult forSuccess(ResourceAllocation allocation) {
        return new ResourceConsumerRunnerResult(allocation, null);
    }

    public static ResourceConsumerRunnerResult forInitializationFailure(
    		ResourceAllocation allocation, Throwable failure) {
        return new ResourceConsumerRunnerResult(allocation, failure);
    }
}
